# -*- coding: UTF-8 -*-

from datetime import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty, get_month_range, CommonTimeUtils
from core.logger import logger

__all__ = ['OaAsset']

class OaAsset(Base, SessionMixin):
    '''
    oa系统的资产流程记录
    '''
    __tablename__ = "oa_asset"
    name = Column(String(64), nullable=False, comment='申请人')
    department = Column(String(32), nullable=False, comment='所属部门')
    application_type = Column(String(32), nullable=False, comment='申请类型')
    create_time = Column(DateTime, default=datetime.now, comment='申请时间')
    close_month = Column(String(16), default=datetime.now, comment='关闭月份')
    price = Column(String(32), nullable=True, comment='工单费用')
    flow_id = Column(String(64), nullable=False, index=True, comment='流程id')
    flow_title = Column(String(128), nullable=False, comment='流程标题')
    cloud_platform = Column(String(32), nullable=True, index=True, comment='云平台')
    cloud_account = Column(String(32), nullable=True, index=True, comment='云平账号')
    asset_names = Column(JSON, nullable=False, default=[], comment='资产名称')
    asset_type = Column(String(32), nullable=False, comment='申请类型')
    
    update_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    comment = Column(String(256), nullable=True, comment='申请原因')



    __table_args__ = (
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<flow_title={self.flow_title}>"


    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }
        return result



    @classmethod
    def get_asset_name(cls, db: Session, asset_type: str, asset_name: str):
        # 获取某一个资产所有的工单信息
        object = db.query(cls).filter(
            cls.asset_type == asset_type,
            func.json_contains(cls.asset_names, str(asset_name)) == 1,
        ).order_by(cls.create_time.desc()).to_dict()
        return object


    @classmethod
    def get_asset_name_by_month(cls, db: Session, asset_type: str, asset_name: str, month: str):
        # 获取一个月某一个资产的工单信息
        object = db.query(cls).filter(
            cls.asset_type == asset_type,
            func.json_contains(cls.asset_names, str(asset_name)) == 1,
            cls.close_month == month
        ).order_by(cls.create_time.desc()).to_dict()
        return object
    
    
    @classmethod
    def get_all_by_month(cls, db: Session, month: str):
        # 获取一个月所有的工单信息
        object = db.query(cls).filter(
            cls.close_month == month
        ).order_by(cls.create_time.desc()).to_dict()
        return object


    @classmethod
    def delete_by_flow_id(cls, db: Session, flow_id: str):
        # 删除某一个流程id的信息
        db.query(cls).filter(
            cls.flow_id == flow_id
        ).delete()
        db.commit()
        return True
    
    
    @classmethod
    def delete_by_month(cls, db: Session, month: str):
        db.query(cls).filter(
            cls.close_month == month
        ).delete()
                
        db.commit()
        return True